/**
 * 申请单详情
 * @author hongwei 2018-09-20
 */
(function (window) {
    'use strict';
    var applyInfo = function (params) {
        $.extend(this.params, params);
        this._init();   //初始化操作
    };

    applyInfo.prototype = {
        //参数
        params : {
            sign_url : '' //签名
            ,sing_flag : false
        }

        ,_init : function () {
            var that = this;

            that.getApplyInfo();    //step01:获取新增出差申请单数据
            that.signatureOn();     //step02:签名操作
        }

        //step01:获取新增出差申请单数据
        ,getApplyInfo : function () {
            var that = this;

            var apply_id = $api.getStorage('apply_id');
            var param = {};
            param.url = Config.travel.applyInfo;
            param.data = {
                id: apply_id
            };
            /*请求申请单列表接口*/
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    //step1:审批轨迹
                    var interText = doT.template($("#apply_tpl").text());
                    $("#approve_info").append(interText(ret.data));

                    //step2:订单信息
                    $("#book_user_name").text(ret.data.book_user_name);
                    $("#travel_application_number").text(ret.data.travel_application_number);
                    $("#travel_site").text(ret.data.travel_site);
                    $("#travel_destination").text(ret.data.travel_destination);
                    $("#travel_time").text(ret.data.travel_time);
                    $("#travel_end_time").text(ret.data.travel_end_time);
                    $("#business_name").text(ret.data.business_name);
                    $("#approve_name").text(ret.data.approve_name);
                    $("#travel_cause").text(ret.data.travel_cause);

                    //step3:图片列表
                    var interTextImageList = doT.template($("#imageListTpl").text());
                    var imgUrlData = $.parseJSON(ret.data.img_url);
                    $("#imageList").append(interTextImageList(imgUrlData));

                    //step4:审核签名模板
                    var interText2 = doT.template($("#approve_sign").text());
                    $("#sign_info").append(interText2(ret.data));

                    //step5:审核操作模板
                    var interText3 = doT.template($("#approve_option_tpl").text());
                    $("#approve_option").append(interText3(ret.data));

                    that.initImg();//step12:点击图片放大
                    that.initApproveButton();    //step13:初始化显示“通过审核”和“驳回申请”按钮
                } else {
                    $toast(ret.msg);
                }
            })
        }

        //step02:签名操作
        ,signatureOn : function () {
            var that = this;

            $('.js-signature').on('jq.signature.changed', function() {
                var sing_flag = true;
                //合并参数
                var sing_flagTemp = {
                    sing_flag : sing_flag
                };
                $.extend(that.params, sing_flagTemp);
            });

        }


        //step11:更改状态“审核/驳回”
        ,changeStatus : function (status) {
            var that = this;

            var travel_id = $api.getStorage('apply_id');
            var param = {};
            param.url = Config.travel.applyExamineApprove;
            if (status === 1) {
                param.data = {
                    travel_id       : travel_id,
                    approved_status : status,
                    dismissal_cause : reason
                };
            } else {
                param.data = {
                    travel_id       : travel_id,
                    approved_status : status,
                    sign_url        : that.params.sign_url
                };
            }

            ajax(param, function(ret) {
                if (ret.code === 1) {
                    $alert('审批成功', function() {
                        screenRotate();
                        setTimeout(function(){
                            location.reload();
                        },500);
                    });
                } else {
                    $toast('审批失败');
                }
            })
        }

        //step12:点击图片放大
        , initImg : function () {
            $("img").on("click", function() {
                var url = $(this).attr("src");
                var html = '';
                html += '<div class="wang-enlarge-plugin-div">';
                html += '<div class="wang-enlarge-cover-div"></div>';
                html += '<div class="wang-enlarge-img-div"><img src="' + url + '"></div>';
                html += '</div>';
                $("body").append(html)
            });
            $(document).on("click", ".wang-enlarge-plugin-div", function() {
                this.remove()
            });
        }

        //step13:初始化显示“通过审核”和“驳回申请”按钮
        ,initApproveButton : function () {
            var that = this;

            var flag = true;
            var reason = '';

            $(".changeStatus").click(function() {
                var status = $(this).find("input").val();
                if (!flag) {
                    return false;
                }
                flag = false;
                if (status === 1) {
                    layer.open({
                        type: 1,
                        title: '选择驳回原因',
                        area: ['300px', '300px'], //宽高
                        content: $("#rejectCause"),
                        btn: '确定',
                        closeBtn: 1,
                        shadeClose: true,
                        yes: function() {
                            reason = $("#rejectCause input:checked").val();
                            that.changeStatus(status);
                            layer.closeAll();
                        }
                    });
                    flag = true;
                } else {
                    $('.js-signature').jqSignature();
                    api.setScreenOrientation({
                        orientation: 'landscape_left'
                    });
                    $('html').addClass('noscroll');
                    layer.open({
                        type: 1,
                        title: '签名审核',
                        area: [api.frameHeight + 'px', '300px'], //宽高
                        offset : ['10px','25px'],//坐标
                        content: $("#signPass"),
                        btn: ['清空', '确定'],
                        closeBtn: 1,
                        yes: function() {
                            that.clearCanvas(); //清空画布
                            return false;
                        },
                        btn2: function() {
                            if (!that.params.sing_flag) {
                                $toast("请签名");
                                return false;
                            }
                            that.saveSignature(status); //保存
                            layer.closeAll();
                            return false;
                        },cancel: function(index, layero){
                            screenRotate();
                            flag = true;
                            layer.close(index);
                            return false;
                        }
                    });
                    flag = true;
                }
            });
        }

        //step14:清空画布
        ,clearCanvas : function () {
            $('.js-signature').jqSignature('clearCanvas');
        }

        //step15:保存签名
        ,saveSignature : function (status) {
            var that = this;

            var sign_url = '';
            $('#signature').empty();
            var canvas = document.getElementsByTagName('canvas');
            var dataUrl = that.canvasToImage(canvas[0], "white");
            var param = {};
            param.url = Config.travel.uploadImgOss;
            param.data = {
                imgData: dataUrl
            };
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    sign_url = ret.data;
                    //合并参数
                    var signUrlTemp = {
                        sign_url : sign_url
                    };
                    $.extend(that.params, signUrlTemp);

                    that.changeStatus(status);     //审核通过操作
                } else {
                    $toast(ret.msg);
                }
            })
        }

        //step16:画布转图片
        , canvasToImage : function (canvas, backgroundColor) {
            //cache height and width
            var w = canvas.width;
            var h = canvas.height;
            var data;

            var context = canvas.getContext('2d');
            if (backgroundColor) {
                //get the current ImageData for the canvas.
                data = context.getImageData(0, 0, w, h);

                //store the current globalCompositeOperation
                var compositeOperation = context.globalCompositeOperation;

                //set to draw behind current content
                context.globalCompositeOperation = "destination-over";

                //set background color
                context.fillStyle = backgroundColor;

                //draw background / rect on entire canvas
                context.fillRect(0, 0, w, h);
            }

            //get the image data from the canvas
            var imageData = canvas.toDataURL("image/png");

            if (backgroundColor) {
                //clear the canvas
                context.clearRect(0, 0, w, h);

                //restore it with original / cached ImageData
                context.putImageData(data, 0, 0);

                //reset the globalCompositeOperation to what it was
                context.globalCompositeOperation = compositeOperation;
            }

            //return the Base64 encoded data url string
            return imageData;
        }
    };

    window.applyInfo = applyInfo;
})(window);
